//
//  HNCourseListSeeTeacherVC.m
//  优学荟管理系统
//
//  Created by edz on 2017/10/31.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HNCourseListSeeTeacherVC.h"
#import "HNCourseListSeeTeacherModel.h"
#import "HNCourseListSeeTeacherCell.h"
#import "HNCourseListSeeTeacherSearchView.h"
#import "TeacherListView.h"

@interface HNCourseListSeeTeacherVC ()<UITableViewDelegate, UITableViewDataSource>
{
    // 表单
    __weak IBOutlet UITableView *_TableView;
    // 数据存放
    NSMutableArray *_DataArr;
}


@property (nonatomic,strong)NSMutableArray *dataSource;

@end

@implementation HNCourseListSeeTeacherVC


- (NSMutableArray *)dataSource {
    
    
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
    
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title = @"查看老师";
    // 配置表单并发起请求
    [self ConfigTableView];
    

}

#pragma mark - Config
/** 配置表单 */
- (void)ConfigTableView {
    
    /** 预注册 */
    [_TableView registerNib:[UINib nibWithNibName:[HNCourseListSeeTeacherCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    /** 预估高度 */
    _TableView.rowHeight = 61*KScale;
    /** 下拉加载 */
    _TableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 每次刷新都重置数组
        [self RefreshDataWithComplete:^(NSMutableArray *Arr) {
            // 得到数据了
            _DataArr = Arr;
            // 刷新界面
            [_TableView reloadData];
        }];
    }];
    [_TableView.mj_header beginRefreshing];
}

#pragma mark - 网络
- (void)RefreshDataWithComplete:(void (^)(NSMutableArray *Arr))Complete {
    
    NSDictionary *Params = @{
                             @"action"      :@"getTeachsersBylessonId",
                             @"lessonId"    :self.lessonId
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {
        [_TableView.mj_header endRefreshing];
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            NSArray *DataArr = Obj[@"t"];
            if (DataArr.count == 0) {
                [SVProgressHUD showErrorWithStatus:@"该课程暂无老师，请添加老师"];
            } else {
                NSMutableArray *Arr = [NSMutableArray array];
                [DataArr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    HNCourseListSeeTeacherModel *Model = [[HNCourseListSeeTeacherModel alloc] init_ValuForKeyWithDict:obj];
                    Model.IsShowDelete = DataArr.count > 1 ? YES:NO;
                    [Arr addObject:Model];
                }];
                Complete ([Arr mutableCopy]);
            }
        } else {
            [SVProgressHUD showSuccessWithStatus:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [SVProgressHUD showErrorWithStatus:NetErr];
        [_TableView.mj_header endRefreshing];
    }];
}

- (void)DeleteTeacherWithID:(NSNumber *)ID Complete:(void (^)())Complete {
    
    [SVProgressHUD showWithStatus:@"请稍候"];
    NSDictionary *Params = @{
                             @"action"  :@"delLessonTeachser",
                             @"id"      :ID
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            [SVProgressHUD showSuccessWithStatus:@"该老师已成功删除!"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 执行界面删除工作
                Complete ? Complete():nil;
            });
        } else {
            [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [SVProgressHUD showErrorWithStatus:NetErr];
    }];
}

#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HNCourseListSeeTeacherModel *Model = _DataArr[indexPath.row];
    HNCourseListSeeTeacherCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    Cell.Model = Model;
    // 删除老师
    Cell.ClickDeleteTeacher = ^(HNCourseListSeeTeacherModel *Model) {
        
        [self ClickDeleteTeacherWithModel:Model IndexPath:indexPath];
    };
    return Cell;
}

#pragma mark - action
/** 添加其他老师 */
- (IBAction)AddTeacher:(UIButton *)sender {
        TeacherListView *View = [[[NSBundle mainBundle]loadNibNamed:@"TeacherListView" owner:nil options:nil] lastObject];
        View.frame = CGRectMake(0, -64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        NSLog(@"%@",self.lessonId);
    
    View.lastreload = ^{
      

        [_TableView.mj_header beginRefreshing];
    };
        View.lessonId = self.lessonId;
        [self.view addSubview:View];
    
   
    //[self getNet:[self.lessonId stringValue]];
}




-(void) getNet:(NSString *)lessonId{
    //http://192.168.0.113:8080/StarShine/ys/yxhUser.do?action=getLessonTeachserList&lessonId=721
    
    NSString *url = [NSString stringWithFormat:@"yxhUser.do?action=getLessonTeachserList&lessonId=%@",lessonId];
    
    
    
    
    NSLog(@"%@  %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        
        
        if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
            
            
            
        }
        
        
        
        
        
        
        
    } Fail:^(NSError *Error) {
        
        
        
        [SVProgressHUD showErrorWithStatus:NetErr];
        
    }];
    
    
//    TeacherListView *View = [[[NSBundle mainBundle]loadNibNamed:@"TeacherListView" owner:nil options:nil] lastObject];
//    View.frame = CGRectMake(0, -64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
//    NSLog(@"%@",self.lessonId);
//
//    View.lessonId = self.lessonId;
//    [self.view addSubview:View];
//
    
    
    
}























/** 点击删除，成功之后动画刷新界面 */
- (void)ClickDeleteTeacherWithModel:(HNCourseListSeeTeacherModel *)Model IndexPath:(NSIndexPath *)IndexPath {
    
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请确认是否删除该任课老师?" preferredStyle:UIAlertControllerStyleActionSheet];
    [Alert addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        // 确认删除
        [self DeleteTeacherWithID:Model.ID Complete:^{
            // 从数组中移除这个Model
            [_DataArr removeObject:Model];
            // 每次源数据变动都要调用这个方法，去设置按钮要不要隐藏
            [self SetModelIsShowDelete];
            // 表单删除这一行
            [_TableView reloadSections:[NSIndexSet indexSetWithIndex:IndexPath.section] withRowAnimation:(UITableViewRowAnimationAutomatic)];
            
        }];
    }]];
    [Alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:nil]];
    [self presentViewController:Alert animated:YES completion:nil];
}


#pragma mark - func
/** 每次源数据变动都要调用这个方法，去设置按钮要不要隐藏 */
- (void)SetModelIsShowDelete {
    
    [_DataArr enumerateObjectsUsingBlock:^(HNCourseListSeeTeacherModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.IsShowDelete = _DataArr.count > 1 ? YES:NO;
    }];
}
@end
